package com.zhk.ScriptManagement.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhk.ScriptManagement.constant.ShiroConstant;
import com.zhk.ScriptManagement.entity.Permission;
import com.zhk.ScriptManagement.entity.User;
import com.zhk.ScriptManagement.entity.vo.UserVo;
import com.zhk.ScriptManagement.mapper.PermissionMapper;
import com.zhk.ScriptManagement.mapper.UserMapper;
import com.zhk.ScriptManagement.service.UserService;
import com.zhk.ScriptManagement.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Optional;

/**
 * @Author: zhouhongkun
 * @Description: 用户service实现类
 * @Date: 2021/4/4 14:29
 */
@Service
public class UserServiceImpl implements UserService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Result login(User user) {
        try{
            User userInfo = userMapper.getUserByUserName(user.getUserName());
            //账号不存在、密码错误
            if (userInfo == null) {
                return Result.error(CodeMsg.USER_NOT_EXSIST,"账号不存在");
            } else if (!userInfo.getPassWord().equals(MD5Util.code(user.getPassWord()))) {
                return Result.error(CodeMsg.PASSWORD_USERNAME_ERROR,"用户名或密码错误");
            } else {
                //生成token，并保存到reids
                String token = TokenUtil.sign(userInfo.getUserName(),userInfo.getUserId());
                userInfo.setToken(token);
                RedisUtil.set(ShiroConstant.LOGIN_SHIRO_CACHE + userInfo.getUserId(),userInfo);
                return Result.success(token);
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error(CodeMsg.SERVER_EXCEPTION,"登录失败");
        }
    }

    @Override
    public Result logout() {
        try{
            Subject sub = SecurityUtils.getSubject();
            User user = (User)sub.getPrincipal();
            sub.logout();
            RedisUtil.del(ShiroConstant.LOGIN_SHIRO_CACHE + user.getUserId());
            return Result.success("退出成功");
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error(CodeMsg.SERVER_EXCEPTION,"退出失败");
        }
    }

    @Override
    public User getUserByUserName(String userName) {
        return userMapper.getUserByUserName(userName);
    }



    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor = Exception.class)
    public Result addUser(User user) {
        try {
            user.setPassWord(MD5Util.code(user.getPassWord()));
            userMapper.insertUser(user);
            Permission permission = new Permission();
            permission.setUserId(user.getUserId());
            permission.setRoleId(2);
            permissionMapper.addPermission(permission);
            return Result.success("添加成功");
        }catch (Exception e){
            log.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus();
            return Result.error(CodeMsg.SERVER_EXCEPTION,"添加失败");
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor = Exception.class)
    public Result updateUser(User user) {
        try {
            user.setPassWord(MD5Util.code(user.getPassWord()));
            userMapper.updateUser(user);
            if(Optional.ofNullable(user.getStates()).isPresent()  && user.getStates() == 0){
                permissionMapper.deletePermission(user.getUserId());
            }
            return Result.success("更新成功");
        }catch (Exception e){
            log.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus();
            return Result.error(CodeMsg.SERVER_EXCEPTION,"更新失败");
        }
    }

    @Override
    public Result getUsers(String size, String num,String realName) {
        try{
            Integer pageSize = null;
            Integer pageNum = null;
            if(Optional.ofNullable(size).isPresent() && Optional.ofNullable(num).isPresent()){
                pageNum = Integer.parseInt(num);
                pageSize = Integer.parseInt(size);
            }
            PageHelper.startPage(pageNum,pageSize);
            List<UserVo> users = userMapper.getUsers(realName);
            PageInfo<UserVo> userPageInfo = new PageInfo<>(users);
            return Result.success(userPageInfo);
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error(CodeMsg.SERVER_EXCEPTION,"查询失败");
        }
    }

    @Override
    public Result getUserByUserId(Integer userId) {
        try{
            UserVo user = userMapper.findUserByUserId(userId);
            return Result.success(user);
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error(CodeMsg.SERVER_EXCEPTION,"查询失败");
        }
    }

}
